import {
	official_appid,
	official_appsecret,
} from '@/config/index.js'
import {
	get,
} from '@/api/request.js'

const weixin_getUserProfile = () => {
	return new Promise((resolve, reject) => {
		uni.getUserProfile({
			desc: "用于完善会员资料",
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				console.log(err);
				reject()
			}
		});
	})
}

const h5_getUserProfile = async () => {
	const code = uni.getStorageSync('code')
	const tokenParams = {
		appid: official_appid,
		secret: official_appsecret,
		code,
		grant_type: 'authorization_code',
	}
	const tokenRes = await get('/api-weixin/sns/oauth2/access_token', tokenParams)
	if (!tokenRes) return
	const access_token = tokenRes.data.access_token || tokenRes.data.data.access_token
	const openid = tokenRes.data.openid || tokenRes.data.data.openid
	if (!access_token || !openid) return
	const params = {
		access_token,
		openid
	}
	const res = await get('/api-weixin/sns/oauth2/access_token', params)
	if (!res) return
	return res
}

const app_getUserProfile = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin', // 或其他登录方式
			success: (res) => {
				uni.getUserInfo({
					provider: 'weixin', // 或其他登录方式
					success: (infoRes) => {
						resolve(infoRes)
					},
					fail: (err) => {
						reject(err);
					}
				})
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}

// 如果是微信小程序端
// #ifdef MP-WEIXIN
const getUserProfile = weixin_getUserProfile
// #endif

// 如果是APP端
// #ifdef APP
const getUserProfile = app_getUserProfile
// #endif

// #ifdef H5
const getUserProfile = h5_getUserProfile
// #endif

module.exports = {
	getUserProfile,
}